package d1_reflect;

import org.junit.Test;

import java.lang.reflect.Constructor;

    public class t1constructor {
        @Test
        public void testGetConstructors() {
            Class c = Student.class;
            //获取类的全部构造器
//        Constructor[] cs = c.getConstructors();//获取所有public修饰的构造器
            Constructor[] cs = c.getDeclaredConstructors();//获取所有声明的构造器
            //遍历构造器对象
            for (Constructor ctor : cs) {
                System.out.println(ctor.getName()+"--->"+ctor.getParameterCount());
            }
        }
        @Test
        public void testGetConstructor() throws Exception {
            Class c = Student.class;
            //获取某个构造器,无参构造器
//        Constructor cs = c.getConstructor();
            Constructor cs = c.getDeclaredConstructor();//所有声明的都可拿
            System.out.println(cs.getName()+"--->"+cs.getParameterCount());//获取名字和参数量
            cs.setAccessible(true);//禁止检查访问权限
            Student s1 = (Student) cs.newInstance();
            System.out.println(s1);

//        Constructor cs2 = c.getConstructor(String.class, int.class,double.class);
            Constructor cs2 = c.getDeclaredConstructor(String.class, int.class,double.class);//获取声名的有参构造器
            System.out.println(cs2.getName()+"--->"+cs.getParameterCount());
            cs2.setAccessible(true);//禁止检查访问权限
            Student s2 = (Student) cs2.newInstance("王巴丹", 12,188.1);
            System.out.println(s2);
        }
    }

